<!--云闪推——成片任务-->
<template>
  <div class="ele-body">
    <task-search :data="data" @search="reload"></task-search>
    <el-card class="m-top10 p-algin10" shadow="never">
      <ele-pro-table
        ref="table"
        size="mini"
        :columns="columns"
        :datasource="datasource"
        :selection.sync="selection"
        :need-page="true"
        :hideOnSinglePage="false"
      >
        <!--头部按钮-->
        <template v-slot:toolbar>
          <el-button type="primary" size="small"
                     @click="piecesSet(1)">
            添加任务
          </el-button>
        </template>

        <!--任务状态插槽-->
        <template v-slot:status="{ row }">
          <div :class="row.status==3 || row.status==2 ? 'status-class' : 'no-status-class'">
            {{ row.status==3?'已完成':row.status==2?'执行中':'未执行' }}</div>
        </template>
        <!--任务进度插槽-->
        <template v-slot:progress="{ row }">
          <el-progress :percentage="row.taskProgressCount || 0"></el-progress>
        </template>
        <!--操作-->
        <template v-slot:action="{ row }">
          <div class="flex-around">
            <el-link
              type="primary"
              :underline="false"
              @click="viewSlices(row)"
            >
              查看成片
            </el-link>
            <!--notTask ： 0.不能终止，2 可以终止-->
            <el-link
              type="danger"
              :underline="false"
              @click.stop="terminationSingle(row)"
              :disabled="row.notTask==0"
            >
              <!--终止任务， 进度进行中 已终止，100%——已完成-->
              {{row.notTask==2 ? '终止任务' : row.taskProgressCount==100 &&row.notTask==0 ? '已完成' : row.taskProgressCount!=100 &&row.notTask==0 ? '已终止' : '' }}
            </el-link>
            <!--
            notTask ： 0.不能终止，2 可以终止
            但任务进度（taskProgressCount）为100 || 终止任务不能终止时（代表已终止），则可以去删除-->
            <el-link
              type="danger"
              :disabled="row.notTask==0 || row.taskProgressCount==100 ? false : true"
              :underline="false"
              @click.stop="delSingle(row)"
            >
              删除
            </el-link>
          </div>
        </template>
      </ele-pro-table>
    </el-card>

    <!--成片配置 弹窗-->
    <btn-configuration
      :data="data"
      :mcList="mcList"
      :musics="musics"
      ref="pieceSet"
      @click="piecesSet"
      :visible.sync="drawer"
      @done="reload">
    </btn-configuration>
  </div>

</template>

<script>
  import TaskSearch from "@/views/lncomingManagement/cameraManage/piecemealTask/components/task-search";
  import BtnConfiguration from "@/views/lncomingManagement/cameraManage/collectMaterials/components/btn-configuration";
  import {queryFolder} from "@/api/lncomingManagement/fileList";
  import {getFileAll, publicFile} from "@/api/creatCenter/material";
  import {queryChipPage,delChipPage,stopTerminateTask} from "@/api/lncomingManagement/cameraManage";
  import {musicCollect, musicList} from "@/api/lncomingManagement/music";
  import {mc} from "@/utils/js/mc_list";

  export default {
    name: "index",
    components: {TaskSearch,BtnConfiguration},
    data(){
      return{
        /*成片配置 start*/
        data:[], //摄像头文件夹查询
        mcList:[], //热榜音乐
        musics:[],  //热榜音乐
        /*成片配置 end*/

        // 当前编辑数据
        current: null,
        // 表格列配置
        columns: [
          /* {
             columnKey: 'selection',
             type: 'selection',
             width: 45,
             align: 'center'
           },*/
          /*{
            prop: 'sortNumber',
            label: '排序',
            align: 'center',
            showOverflowTooltip: true,
            width: 60
          },
*/
          {
            prop: 'taskName',
            label: '任务名称',
            align: 'center',
            width:200,
            showOverflowTooltip: true
          },
          {
            prop: 'folderName',
            label: '文件夹名',
            width:200,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'status',
            label: '任务状态',
            width:200,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'status'
          },
          {
            slot: 'progress',
            prop: 'progress',
            label: '任务进度 ',
            align: 'center',
            width:300,
            showOverflowTooltip: true,
          },
          {
            prop: 'createTime',
            label: '创建时间 ',
            align: 'center',
            showOverflowTooltip: true,
          },
          {
            prop: 'endTime',
            label: '结束时间 ',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (_row, _column, cellValue) => {
              return cellValue ? cellValue : '--';
            }
          },

          {
            label: '操作',
            columnKey: 'action',
            width: 260,
            align: 'center',
            resizable: false,
            slot: 'action',
            hideInSetting: true,
            showOverflowTooltip: true,
            fixed: 'right'
          }
        ],
        // 表格选中数据
        selection: [],

        drawer:false,

        //获取用户名
        username:this.$store.state.user.info.username,
        /*成片/采集配置 弹框 end */
      }
    },
    // 路由刷新
    activated(){
      this.init()
      this.query();
    },
    created() {
    },
    methods:{
      // 热榜音乐数据
      async init () {
        let res = await musicCollect(this.username)
        console.log("分类res=======",res)
        res['mc_list']
          ? mc.find((item) => {
            let mcItem
            (mcItem = res['mc_list'].find((m) => {
              return item === m.name
            })) ? this.mcList.push(mcItem) : void 0
          }) : console.log('加载分类失败11')
        let music
        this.mcList.length > 0
          ? music = await musicList(this.mcList[0]['id_str'],this.username) : console.log('分类音乐加载失败22')
        music && music['music_list']
          ? this.musics = music['music_list'] : console.log('分类音乐加载失败33')
        console.log("加载分类mcList,this.musics ",this.mcList,this.musics )
      },

      /*成片管理数据查询 start*/


      // 成片配置  hideType_ 1:自动成片 2:采集素材
      piecesSet(hideType){
        this.drawer=true
        this.$nextTick(()=>{
          this.$refs['pieceSet'].show(hideType)
        })
        console.log(" this.drawer", this.drawer,'data',this.data,'hideType---',hideType)
      },

      /* 查询文件列表 */
      async query() {
        this.data = [];
        //用户所创建的文件
        let userData = await queryFolder({
          merchantId: this.$store.state.user.info.merchantId,
          //父级目录：初次传0
          parentId: this.parentId, // 商户id
          // types 1.自动成片  2.采集
          types:1
        })
        console.log('userData', userData)
        //es6支持...数组合并
        this.data  = [...userData];
      },
      /*成片管理数据查询 end*/


      /* 如果想在数据源里面获取到接口返回的数据, 增加 async 和 await */
      async datasource({ page, limit, where, order }) {
        const result = await queryChipPage({ ...where, ...order, page, limit,...this.activityList,
          merchantId: this.$store.state.user.info.merchantId,  // 商家id
          types:1 // 1：自动成片 2：采集素材
        });
        return result;  // 这里返回的数据要包含 list 和 count 两个字段，字段名称可以通过 response 属性配置
      },
      /* 刷新表格 */
      reload(where) {
        this.$refs.table.reload({ page: 1, where: where });
      },

      // 查看成片
      viewSlices(row){
        console.log("row.id ========", row.id )
        this.$router.push({path:'/lncomingManagement/cameraManage/automaticSlicing',query:{folderId: row.folderId }})
      },
      // 终止任务——如果进度为100则不能终止
      terminationSingle(row){
        this.$confirm('此操作将永久终止该任务, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          stopTerminateTask({
            chipConfigurationId:row.id,
          })
            .then((data) => {
              this.reload()
              this.$message.success('终止任务成功!');
            })
            .catch((e) => {
              this.$message.error(e);
            });
        }).catch(() => {
          this.$message.info('已取消终止任务');
        });
      },
      /* 删除 */
      delSingle(row) {
        let ids=[]
        ids.push(row.id)
        console.log("ids====",ids)
        this.delGroups(ids)
      },
      delGroups(ids){
        this.$confirm('此操作将永久删除该任务, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delChipPage({
            ids:ids,
            // types 1.自动成片  2.采集 不需要
          })
            .then((data) => {
              this.reload()
              this.$message.success('删除成功!');
            })
            .catch((e) => {
              this.$message.error(e);
            });
        }).catch(() => {
          this.$message.info('已取消删除');
        });
      },
    }
  }
</script>

<style scoped>
  .no-status-class,.status-class{
    white-space: nowrap;
    position: relative;
    box-sizing: border-box;
    cursor: default;
    display: inline-flex;
    align-items: center;
    flex-wrap: nowrap;
    padding: 0 7px;
    height: 28px;
    border-radius: 2px;
    line-height: 1;
  }
  .no-status-class{
    color: rgb(51, 54, 57);
    background-color: #eee;
  }
  .status-class{
    color: #18a058;
    background-color: rgba(20, 142, 77, 0.12);
  }
</style>
